package com.zj.leetcode.medium.tree;

/**
 * @program: algorithm
 * @description: 把二叉搜索树转换为累加树
 * 538 convert-bst-to-greater-tree
 * @author: Zhang Bo
 * @create: 2022-07-07 19:36:27
 **/
public class ConvertBstToGreaterTree {
    public static void main(String[] args) {
        Solution solution = new ConvertBstToGreaterTree().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        int newVal = 0;
        public TreeNode convertBST(TreeNode root) {
            if(root == null){
                return null;
            }

            this.dfs(root);
            return root;
        }

        public void dfs(TreeNode node) {

            if (node != null) {
                if (node.right != null) {
                    this.dfs(node.right);
                }
                node.val = newVal + node.val;
                newVal = node.val;
                if(node.left != null){
                    this.dfs(node.left);
                }

            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}

